package me.sealer.ssm.service.impl;

import me.sealer.ssm.constant.RoleConstant;
import me.sealer.ssm.mapper.RoleMapper;
import me.sealer.ssm.mapper.UserMapper;
import me.sealer.ssm.mapper.UserRoleMapper;
import me.sealer.ssm.model.Role;
import me.sealer.ssm.model.User;
import me.sealer.ssm.model.UserRole;
import me.sealer.ssm.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author sealer
 * @date 2016/09/27
 */
@Service
public class UserServiceImpl implements UserService {
    private final UserMapper userMapper;
    private final RoleMapper roleMapper;
    private final UserRoleMapper userRoleMapper;

    public UserServiceImpl(UserMapper userMapper, RoleMapper roleMapper, UserRoleMapper userRoleMapper) {
        this.userMapper = userMapper;
        this.roleMapper = roleMapper;
        this.userRoleMapper = userRoleMapper;
    }

    @Override
    public List<User> queryUserList() throws Exception {
        //调用mapper类中的selectByExample方法，如果传入类型为null，则表示无条件查找
        List<User> users = userMapper.selectByExample(null);
        return users;
    }

    @Override
    public User findUserByUsername(String username) {
        return userMapper.findUserByUsername(username);
    }

    @Override
    public void updateUser(User user) {
        userMapper.updateUser(user);
        return;

    }

    @Override
    public boolean insert(User user) {
        userMapper.insert(user);
        return true;
    }

    @Override
    public User findUserByPhoneNumber(String phoneNumber) {
        return userMapper.findUserByPhoneNumber(phoneNumber);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean createUser(User user) {
        String password = user.getPassword();
        user.setPassword(null);

        boolean successInsertUser = insert(user);

        if (!successInsertUser) {
            return false;
        }

        User userSelected = findUserByUsername(user.getUsername());
        int id = userSelected.getId();

        // 检验通过， 修改密码， 更新数据库。
        String passwordHex = DigestUtils.md5DigestAsHex((id + password).getBytes(StandardCharsets.UTF_8));
        User newUser = User.builder()
                .password(passwordHex)
                .id(id)
                .build();

        updateUser(newUser);

        Role role = roleMapper.getRoleByName(RoleConstant.ROLE_NORMAL);
        int roleId = role.getId();
        UserRole userRole = UserRole.builder()
                .roleId(roleId)
                .userId(id)
                .build();
        userRoleMapper.insert(userRole);

        return true;
    }

    @Override
    public User findUserByEmail(String email) {
        return userMapper.findUserByEmail(email);
    }
}
